package com.shengwei.truck.driver.view.ui.task;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Toast;

import androidx.lifecycle.Observer;

import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.task.JsonSearchUserData;
import com.shengwei.truck.driver.databinding.ActivityShareForwardBinding;
import com.shengwei.truck.driver.utils.CommonUtil;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.vm.ShareForwardViewModel;

import java.lang.ref.WeakReference;

/**
 * 分享、转派任务
 */
public class ShareForwardActivity extends BaseActivity<ShareForwardViewModel, ActivityShareForwardBinding> implements View.OnClickListener {
    private String mMobileNum;
    private int mFromPage = -1;
    private String mTaskId;
    private String mTargetUserId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        getLastIntent();
        initLiveDataObersve();
    }

    private void initView() {
        mDataBinding.btSearch.setOnClickListener(this);
        mDataBinding.btShareForward.setOnClickListener(this);
        mDataBinding.imgBtClear.setOnClickListener(this);

        mDataBinding.edtMobileNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    if (mDataBinding.imgBtClear.getVisibility() == View.GONE) {
                        mDataBinding.imgBtClear.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    mDataBinding.imgBtClear.setVisibility(View.GONE);
                }
            }
        });
    }


    /**
     * 获取上页传递过来的数据
     */
    public void getLastIntent() {
        Intent i = this.getIntent();
        Bundle bundle = i.getExtras();
        if(bundle != null) {
            mFromPage = bundle.getInt("pageFrom");
            mTaskId = bundle.getString("id");
            String title;
            if(mFromPage == 1) { //转派
                title = this.getResources().getString(R.string.task_forward);
                String instructionForward = ShareForwardActivity.this.getResources().getString(R.string.instruction_forwad);
                mDataBinding.btShareForward.setText(R.string.forward);
                mDataBinding.tvInstruction.setText(instructionForward);
            }
            else{
                title = this.getResources().getString(R.string.task_share);
                String instructionShare = ShareForwardActivity.this.getResources().getString(R.string.instruction_share);
                mDataBinding.tvInstruction.setText(instructionShare);
                mDataBinding.btShareForward.setText(R.string.share);
            }
            setToolBar(true,true,title);
        }
    }
    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {

        mViewModel.getSearchUserLiveData().observe(this, new Observer<Result<JsonSearchUserData>>() {
            @Override
            public void onChanged(Result<JsonSearchUserData>searchUserDataResult) {
                searchUserDataResult.handler(new OnCallback<JsonSearchUserData>() {
                    @Override
                    public void onSuccess(JsonSearchUserData data) {
                       if(data != null) {
                           mDataBinding.searchResultLayout.setVisibility(View.VISIBLE);
                           String personName = data.getRealName();
                           mTargetUserId = data.getUserId();

                           if(!TextUtils.isEmpty(personName)){
                               mDataBinding.tvPersonName.setText(personName);
                           }
                           else{
                               mDataBinding.tvPersonName.setText(mMobileNum);
                           }

                           CommonUtil.loadRoundPic(data.getAvatar(),mDataBinding.imvHeadPhoto,getApplicationContext());
                       }
                    }
                });
            }
        });


        mViewModel.getShareForwardLiveData().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String>searchUserDataResult) {
                searchUserDataResult.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                       // if(data != null) {
                            String shareForwardTip = null;
                            if(mFromPage == 1) { //1转派
                                shareForwardTip = ShareForwardActivity.this.getResources().getString(R.string.forward_task_ok);
                            }
                            else{ //2分享
                                shareForwardTip = ShareForwardActivity.this.getResources().getString(R.string.share_task_ok);
                            }
                            Toast.makeText(ShareForwardActivity.this,shareForwardTip,Toast.LENGTH_SHORT).show();
                            finish();
                      //  }
                    }
                });
            }
        });
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_share_forward;
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btSearch) {
            mMobileNum = mDataBinding.edtMobileNum.getText().toString();
            boolean isCorrect = checkInput();
            if(isCorrect){
                mViewModel.searchUserByMobile(mMobileNum,mTaskId);
            }
        }
        else if(v.getId() == R.id.btShareForward) { //任务转派 or共享
            if(!TextUtils.isEmpty(mTaskId) && !TextUtils.isEmpty(mTargetUserId) && mFromPage != -1)
                mViewModel.shareForward(mTaskId,mTargetUserId,mFromPage);
        }
        else if(v.getId() == R.id.imgBtClear){
            clearContent();
        }
    }


    /**
     * 清空输入框
     */
    public void clearContent() {
        mDataBinding.edtMobileNum.setText("");
        mDataBinding.imgBtClear.setVisibility(View.GONE);
        mDataBinding.searchResultLayout.setVisibility(View.GONE);
    }

    /**
     * 检查输入内容是否正确
     */
    public boolean checkInput()
    {
        boolean isCorrect = true;
        WeakReference<Context> weakReferenceContext = new WeakReference<>(ShareForwardActivity.this);
        //手机号
        if(isCorrect) {
            isCorrect = CommonUtil.checkMobile(mMobileNum,weakReferenceContext,true);
        }
        return isCorrect;
    }
}